/**
 * 
 */
package com.srini.servlets;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.FormulaEvaluator;

import com.srini.pojos.LoggedInUser;
import com.srini.pojos.MultiValObject;
import com.srini.util.AppUtil;
import com.srini.util.ConnectionUtil;
import com.srini.util.LeaveHolyDays;
import com.srini.util.TRMSUtil;
import com.vssr.persist.DomainObject;
import com.vssr.persist.exception.DomainException;

/**
 * @author Sriniz
 * 
 */
public class GroupExecuteAction extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private ZipOutputStream zos = null;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		System.out.println("Executing group actions.........");
		// try {
		String action = req.getParameter("action");
		List<MultiValObject> checkList = new ArrayList<MultiValObject>();
		List<Object> userList = null;
		String index, userId, month, strMonth, fileName = null, userName = null, query;
		int formType;
		HSSFWorkbook workBook = null;
		Map days = null;
		MultiValObject mvObj = null;
		Enumeration en = req.getParameterNames();
		while (en.hasMoreElements()) {
			String key = en.nextElement().toString();
			mvObj = new MultiValObject();
			if (key.startsWith("check_")) {
				mvObj.setIndex(key.substring(key.lastIndexOf("_") + 1));
				mvObj.setValue(req.getParameter(key));
				checkList.add(mvObj);
			}
		}
		resp.setContentType("application/zip");
		resp.addHeader("Content-Disposition", "attachment; filename="
				+ "AllReports.zip");
		zos = new ZipOutputStream(resp.getOutputStream());

		Connection conn = new ConnectionUtil().getConnection();
		Calendar cal;
		if (!AppUtil.isEmpty(action)
				&& action.equalsIgnoreCase("generateSummary")) {
			for (int i = 0; i < checkList.size(); i++) {
				mvObj = checkList.get(i);
				index = mvObj.getIndex();
				userId = mvObj.getValue();
				query = "select * from usertable where id=" + userId;
				try {
					userList = DomainObject.getDBRecords(new LoggedInUser(),
							query, conn);
				} catch (DomainException e) {
					e.printStackTrace();
				}
				cal = Calendar.getInstance();
				cal.set(Calendar.DATE, 1);
				LoggedInUser user = (LoggedInUser) userList.get(0);
				month = String.valueOf(cal.get(Calendar.MONTH));
				strMonth = DateFormatSymbols.getInstance().getMonths()[cal
						.get(Calendar.MONTH)];
				formType = Integer.valueOf(req.getParameter("select" + index)
						.toString());
				days = LeaveHolyDays.getHolidays(user.getId(),
						new ConnectionUtil().getConnection());
				workBook = TRMSUtil.getInstance().generateReimbursementForm(
						user, cal, days);
				FormulaEvaluator evaluator = workBook.getCreationHelper()
						.createFormulaEvaluator();
				HSSFCell cell = workBook.getSheetAt(0).getRow(40).getCell(5);
				evaluator.evaluateFormulaCell(cell);
				double val1 = cell.getNumericCellValue();
				cell = workBook.getSheetAt(0).getRow(40).getCell(7);
				evaluator.evaluateFormulaCell(cell);
				double val2 = cell.getNumericCellValue();
				cell = workBook.getSheetAt(0).getRow(42).getCell(7);
				evaluator.evaluateFormulaCell(cell);

				double val3 = cell.getNumericCellValue();
				System.out.println(user.getUserInfo().getFullDisplayName()
						+ " " + val1 + "   " + val2 + "  " + val3);
			}
		} else {

			for (Iterator<MultiValObject> iterator = checkList.iterator(); iterator
					.hasNext();) {
				mvObj = iterator.next();
				index = mvObj.getIndex();
				userId = mvObj.getValue();
				query = "select * from usertable where id=" + userId;
				try {
					userList = DomainObject.getDBRecords(new LoggedInUser(),
							query, conn);
				} catch (DomainException e) {
					e.printStackTrace();
				}
				cal = Calendar.getInstance();
				cal.set(Calendar.DATE, 1);
				LoggedInUser user = (LoggedInUser) userList.get(0);
				month = req.getParameter("selectedMonth" + index);
				int intMonth = Integer.parseInt(month);
				cal.set(Calendar.MONTH, intMonth);
				strMonth = DateFormatSymbols.getInstance().getMonths()[intMonth];
				formType = Integer.valueOf(req.getParameter(
						"selectRadio" + index).toString());
				days = LeaveHolyDays.getHolidays(user.getId(),
						new ConnectionUtil().getConnection());
				userName = user.getUserInfo().getFullName();
				if (AppUtil.isEmpty(userName)) {
					userName = user.getUserName();
				}
				switch (formType) {
				case 0:
					workBook = TRMSUtil.getInstance()
							.generateReimbursementForm(user, cal, days);
					fileName = userName + "_Reimbursement_Details_" + strMonth
							+ ".xls";
					writeWorkbook(workBook, fileName);
					break;
				case 1:
					workBook = TRMSUtil.getInstance().generateCashVoucher(user,
							cal, days);
					fileName = userName + "_Cash_Voucher_" + strMonth + ".xls";
					writeWorkbook(workBook, fileName);
					break;
				default:
					workBook = TRMSUtil.getInstance().generateCashVoucher(user,
							cal, days);
					fileName = userName + "_Cash_Voucher_" + strMonth + ".xls";
					writeWorkbook(workBook, fileName);
					cal = Calendar.getInstance();
					cal.set(Calendar.DATE, 1);
					cal.set(Calendar.MONTH, intMonth);

					workBook = TRMSUtil.getInstance()
							.generateReimbursementForm(user, cal, days);
					fileName = userName + "_Reimbursement_Details_" + strMonth
							+ ".xls";
					writeWorkbook(workBook, fileName);
					break;
				}
			}
			closeResources(resp, fileName);
		}
		/*
		 * }catch (Exception e) { throw new DMSException(); }
		 */
	}

	private void writeWorkbook(HSSFWorkbook workBook, String fileName)
			throws UnsupportedEncodingException, FileNotFoundException,
			IOException {
		String decodedFileName = URLDecoder.decode(fileName, "UTF-8");
		ZipEntry ze = new ZipEntry(decodedFileName);
		zos.putNextEntry(ze);
		workBook.write(zos);
		zos.closeEntry();
	}

	private void closeResources(HttpServletResponse resp, String file)
			throws IOException {

		zos.close();

	}
}
